<!--
 * @Author: Dorange.Wang
 * @Date: 2021-05-11 14:16:27
 * @LastEditors: wangming
 * @LastEditTime: 2021-07-31 11:11:27
 * @Description: file content
-->
<template>
  <el-upload
    class="custom-upload"
    action=""
    accept=".xls,.xlsx"
    :show-file-list="false"
    :http-request="handleHttpRequest"
    v-loading="uploadLoading"
  >
    <slot></slot>
  </el-upload>
</template>

<script>
import ImportResult from "./result";
export default {
  name: "CommonImport",
  props: {
    size: {
      type: Number,
      default: 50,
    },
    importApi: {
      // 导入对应的api
      type: Function,
      required: true,
    },
    importUrl: {
      // 导入对应的url、会覆盖api中配置的url（用于导入时提供query参数）
      type: String,
      default: "",
    },
    queryParams: {
      // query参数
      type: Object,
      default: () => {},
    },
    template: {
      // 模板名称
      type: String,
      default: "",
    },
  },
  data() {
    return {
      uploadLoading: false,
    };
  },
  methods: {
    downLoadTemplate() {
      // 后续增加通用模板下载方法
    },

    handleHttpRequest(param) {
      const file = param.file;

      const type = file.name.split(".").pop().toLowerCase();
      if (!["xls", "xlsx"].includes(type)) {
        this.$message.error("只能上传xls/xlsx格式的文件");
        return false;
      }

      const { size } = this;
      const fileSize = file.size / 1024 / 1024;
      const isLt = fileSize < size;
      if (!isLt) {
        const max = size < 1 ? size * 1000 : size;
        const unit = size < 1 ? "KB" : "MB";
        this.$message.error(`文件大小不能超过 ${max}${unit}`);
        return false;
      }

      const formData = new FormData();
      formData.append("file", file);
      this.uploadLoading = true;
      this.importApi(formData, {
        ...this.queryParams,
        confirm: false,
      })
        .then((res) => {
          ImportResult.open(res, () => {
            this.importApi(formData, {
              ...this.queryParams,
              confirm: true,
            }).then((res) => {
              if (res.oksize < 1) {
                return;
              }
              ImportResult.close();
              this.$emit("ok");
            });
          });
        })
        .finally(() => {
          this.uploadLoading = false;
        });
    },
  },
};
</script>

<style lang="scss">
.custom-upload .el-loading-spinner {
  margin-top: -16px;
  .circular {
    height: 32px;
    width: 32px;
  }
}
</style>
